/**
 * 好友相关接口
 */

import { get, post, del } from '@/utils/request'

// API 通用响应结构
interface ApiResponse<T> {
  success: boolean
  statusCode: number
  message: string
  data: T
}

// 好友状态枚举
export enum FriendshipStatus {
  PENDING = 'pending',    // 待接受
  ACCEPTED = 'accepted',  // 已接受
  REJECTED = 'rejected',  // 已拒绝
  BLOCKED = 'blocked'      // 已拉黑
}

// 用户信息（搜索结果）
export interface SearchUserInfo {
  id: number
  username?: string
  email?: string
  avatar?: string
  bio?: string
  friendshipStatus: FriendshipStatus | null  // 好友状态
}

// 搜索结果响应
export interface SearchUsersResponse {
  data: SearchUserInfo[]
  total: number
  page: number
  limit: number
  totalPages: number
}

// 好友信息
export interface FriendInfo {
  id: number
  username?: string
  email?: string | null
  avatar?: string | null
  bio?: string | null
}

// 好友列表响应
export interface FriendListResponse {
  data: FriendInfo[]
  total: number
  page: number
  limit: number
  totalPages: number
}

// 发送好友请求参数
export interface SendFriendRequestParams {
  friendId: number
  remark?: string
}

/**
 * 搜索用户（用于添加好友）
 */
export const searchUsers = async (
  keyword: string,
  page: number = 1,
  limit: number = 20
): Promise<ApiResponse<SearchUsersResponse>> => {
  const queryParams: any = {
    keyword,
    page: String(page),
    limit: String(limit)
  }

  const response = await get<ApiResponse<SearchUsersResponse>>(
    '/friends/search',
    queryParams
  )

  return response
}

/**
 * 发送好友请求
 */
export const sendFriendRequest = async (
  params: SendFriendRequestParams
): Promise<void> => {
  await post('/friends/request', params)
}

/**
 * 获取好友列表
 */
export const getFriendsList = async (
  page: number = 1,
  limit: number = 20
): Promise<ApiResponse<FriendListResponse>> => {
  const queryParams: any = {
    page: String(page),
    limit: String(limit)
  }

  const response = await get<ApiResponse<FriendListResponse>>(
    '/friends/list',
    queryParams
  )

  return response
}

/**
 * 检查是否为好友
 */
export const checkIsFriend = async (userId: number): Promise<boolean> => {
  const response = await get<boolean>(`/friends/check/${userId}`)
  return response
}

/**
 * 接受好友请求
 */
export const acceptFriendRequest = async (friendshipId: number): Promise<void> => {
  await post(`/friends/request/${friendshipId}/accept`, {})
}

/**
 * 拒绝好友请求
 */
export const rejectFriendRequest = async (friendshipId: number): Promise<void> => {
  await post(`/friends/request/${friendshipId}/reject`, {})
}

